import odoo from './odoo'

import session from './session'

// user login
const jsonUserLogin = {
  url: '/api/login',
  type: 'post',
  response: config => {
    // eslint-disable-next-line object-curly-spacing
    const { params = {} } = config.body

    const { db, login, password } = params
    const user_obj = odoo.env('res.users')

    const uid = user_obj.authenticate(db, login, password)
    console.log('xxxxx,uid', uid)
    if (!uid) {
      const error = {
        data: {
          message: 'Access denied'
        }
      }

      return jsonrpc_error(config.body, error)
    }

    session.uid = uid

    const userinfo = user_obj.get_userinfo(uid)
    return jsonrpc(config.body, userinfo)
  }
}

// user logout
const jsonUserLogout = {
  url: '/api/logout',
  type: 'post',
  response: config => {
    return jsonrpc(config.body, true)
  }
}

const jsonrpc = (body, result) => {
  const { jsonrpc, id } = body
  return { jsonrpc, id, result }
}

const jsonrpc_error = (body, error) => {
  const { jsonrpc, id } = body
  return { jsonrpc, id, error }
}

// json api
const jsonAPI = {
  url: '/api/call',
  type: 'post',
  response: config => {
    // eslint-disable-next-line object-curly-spacing
    const { jsonrpc, id, params = {} } = config.body
    const { model, method, args, kwargs } = params

    // console.log('mock: ', model, method, args, kwargs)

    const res = { jsonrpc, id }
    const Model = odoo.env(model)
    // console.log('mock 1: ', model, method, Model)

    if (!Model) {
      res.error = { message: `no model: ${model}` }
    } else if (!Model[method]) {
      res.error = { message: `model ${model} have not mehtod: ${method}` }
    } else {
      res.result = Model[method](...args, kwargs)
    }

    // console.log('mock ok: ', model, method, args, kwargs, res)

    return res
  }
}

export default [jsonUserLogin, jsonUserLogout, jsonAPI]
